var participantsList = function() {
  this.inactive = false;
  this.overlay = null; 
}

//Add by brian 2013.01.31 :: Send broadcast message to all participant
function sendBroadcastMessage() {
	var message = document.formParticipant.PrivateMessage.value;
	gapi.hangout.data.sendMessage(message);
}

//Add by brian 2013.01.30 :: Send private message to selected participant
function sendMessage() {
  var sel_radio_text = $("input[name='Radio']:checked").attr('displayName');
  var sel_radio_value = $("input[name='Radio']:checked").attr('value');
  var msgID = window.myDisplayName;
  var msgTxt = document.formParticipant.PrivateMessage.value; 
  var usrIDs = sel_radio_value;

  console.log(usrIDs);
  //Support user sent private message
  if( sel_radio_value != undefined && sel_radio_value != window.myPersonID && ($("input[name='Radio']:checked").attr('id') != 'all'))
	msgID += ' to ' + sel_radio_text;

  //Avoid user select own, if user select own show message send to all participant
  if( window.myPersonID == usrIDs )
	usrIDs = 'all';

  //Construct message
  var thisMsg = {"msgID" : msgID, "SusrID": window.myPersonID, "RusrID": usrIDs, "persists": true, "msgTxt": msgTxt};
  var tstThisMsg = JSON.stringify(thisMsg);
  gapi.hangout.data.setValue("MsgMsg", tstThisMsg);

}

//Add by brian 2013.02.19 :: Clean all chat room message
function cleanMessage() {
  window.arrMessages[0] = '';
  var container = $('#ReceiveMessage');
  container.html('');
}

//Add by brian 2013.01.30 :: Receive broadcast message
function GTKonMessageReceived(event) {
  var recvMessage = JSON.parse(event.message);
  gapi.hangout.layout.displayNotice(recvMessage, true);
}

//Receive chat room mesage
function GTKshowMsgReceived(event) {
  var theMsg = gapi.hangout.data.getValue("MsgMsg");
  //innerContent use by convert msg text to HTML format
  var innerContent = '';
  if(theMsg != undefined){
    var objMessage = JSON.parse(theMsg);
	//Convert message string to html style
	if(objMessage["msgID"]){
		var msg = '';
		//If message target is me, i will receive it.
		console.log('Receive4: ' + objMessage["RusrID"]);
		if( objMessage["RusrID"].match('all') || objMessage["RusrID"] == window.myPersonID || objMessage["SusrID"] == window.myPersonID){
			//If message is private message, i will text color style set #FF9933
			if( objMessage["RusrID"] == window.myPersonID || objMessage["SusrID"] == window.myPersonID ) {
				msg += '<span style="color:#FF9933">';
				msg += objMessage["msgID"] + ' : ' + objMessage["msgTxt"];
				msg += '</span>'
			}
			else {
				msg += objMessage["msgID"] + ' : ' + objMessage["msgTxt"];
			}
			
			//Check client message array has defined
			if(window.arrMessages[0] != undefined)
				window.arrMessages[0] = window.arrMessages[0] + '<br>' + msg;
			else
				window.arrMessages[0] = msg;
			console.log(window.arrMessages[0]);
			innerContent += window.arrMessages[0];
			console.log(innerContent);
			//Reflash receive message div		
			var container = $('#ReceiveMessage');
			container.html(innerContent);
		}
    }
  }
}

function GTKonStateChange(event) {
  var theKeys = event.addedKeys;
  var theKey, theValue;
  for(var i = 0; i < theKeys.length; i++){
    theKey = event.addedKeys[i].key;
    theValue = event.addedKeys[i].value;
    if(theKey!=undefined){
      switch(theKey){
        case "MsgMsg":
          GTKshowMsgReceived();
          break;
      }
    }
  }
}

function GTKonParticipantsChange() {
	showParticipants();
}

// Add by brian 2013.01.28 :: Show video conference member.
function showParticipants() {
	
  /*
	Init participants icons
  */
  var personBIcon = {primary: 'ui-icon-person', secondary: null};
  var allRIcon = {primary: 'ui-icon-home', secondary: null};
  
  var participants = gapi.hangout.getParticipants();

  var retVal = '<table width=200 border=0>';

  retVal += '<tr><td><div id="Radio">';
  //Step1. Construct participant list html object
  for (var index in participants) {
    var participant = participants[index];

    if (!participant.person) {
	  alert('A participant not running this app');
    }
	
	retVal += '<span title="' + participant.person.displayName + '" style="height:30px;width:30px"><input type="radio" id="'+ participant.person.id +'" name="Radio" value=' + participant.person.id + ' displayName="'+ participant.person.displayName +'"/><label for="'+ participant.person.id +'" style="height:30px;width:30px"></label></span>';
  }
  
  //Step2. Construct group radio object
  retVal += '<span title="All" style="height:30px;width:30px"><input type="radio" id="all" name="Radio" value="all" checked /><label for="all" style="height:30px;width:30px"></label></span></div></td></tr>';
  retVal += '</table>';
  var container = $('#participantsDiv');
  container.html(retVal); //Actual construct html code to div container
  
  $('#all').button({icons: allRIcon});
  
  //Step3. Modify participants icon
  for (var index in participants) {
    var participant = participants[index];
	if( window.myPersonID == participant.person.id){
		$('#'+participant.person.id).button({icons: personBIcon});
		console.log("window.myPersonID = " + window.myPersonID);
	}else{
		$('#'+participant.person.id).button({icons: personBIcon});
		console.log("participant.person.id = " + participant.person.id);
	}
  }
	//console.log("participant.person.id 2 = ",participant.person.id);
	//$('#'+participant.person.id).button({icons: personBIcon});
}

participantsList.prototype.init = function() {
  //Register all event function
  gapi.hangout.data.onMessageReceived.add(GTKonMessageReceived);
  gapi.hangout.data.onStateChanged.add(GTKonStateChange);
  gapi.hangout.onParticipantsChanged.add(GTKonParticipantsChange);
		  
  var container = $('#content-wrap5');
  container.html('');
  //Create a participants list header
  container.append('<fieldset><legend><h3>Participants List</h3></legend><div id=participantsDiv></div></fieldset>')
  
  
  //Display
  showParticipants();

  //Create a chat room header
  container.append('<h3>Chat Room</h3>');
  container.append('<input name="PrivateMessage" type="text"></input>');
  container.append('<input type="button" id="submitMessage" name="submitMessage" value="send" onclick="sendMessage()"></input>');
  container.append('<input type="button" id="clearMessage" name="clearMessage" value="clean" onclick="cleanMessage()"></input>');
  container.append('<div id="ReceiveMessage" style="OVERFLOW: scroll; WIDTH:300px; HEIGHT: 600px;"></div>');
}
